const Koa = require("koa");
const axios = require('axios');
const app = new Koa();


// 处理跨域
const cors = require("@koa/cors");
// 连接数据库
require("./models/mongo.js");
const serve = require("koa-static"); // https://github.com/koajs/static

// 引入发送邮件
require('./node-sendmail.js');


// 静态资源
app.use(serve("./public"));
// 图片文件夹
app.use(cors());
app.use(serve("./uploads"));
app.use(serve("./shopimage"));

// 分文件的路由
const apiRouter = require("./routes/api.js");
const loginRouter = require("./routes/login.js");
const petsRouter = require("./routes/pet.js");
const newsRouter = require("./routes/news.js");
const shopRouter = require("./routes/shop.js");
const orderRouter = require("./routes/order.js");
const gouwuRouter = require("./routes/gouwu.js");


app.use(orderRouter.routes());
app.use(apiRouter.routes());
app.use(loginRouter.routes());
app.use(petsRouter.routes());
app.use(newsRouter.routes());
app.use(shopRouter.routes());
app.use(gouwuRouter.routes());


// // 创建 WebSocket 连接
const { WebSocket, WebSocketServer } = require('ws');
// import { WebSocketServer } from 'ws';

// // 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 3300 });
const rooms = {};

// 监听连接事件
wss.on('connection', function connection(ws) {
    ws.on('error', console.error);

    // 监听接收到的消息
    ws.on('message', function message(data) {
        const parsedData = JSON.parse(data);
        // console.log(parsedData.roomId);

        if (parsedData.type === 'message') {
            const { roomId, message } = parsedData;

            // 如果客户端发送了加入房间的请求
            if (parsedData.action === 'join') {
                // 将客户端加入指定的房间
                if (!rooms[roomId]) {
                    rooms[roomId] = new Set();
                }
                rooms[roomId].add(ws);
                // console.log(`Client joined room ${roomId}`);
            }

            // 向指定房间广播消息
            if (rooms[roomId]) {
                rooms[roomId].forEach(function (client) {
                    if (client.readyState === WebSocket.OPEN) {
                        client.send(JSON.stringify({ message }));
                    }
                });
            }
        } else {
            console.log('received: %s', data);
            wss.clients.forEach(function each(client) {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    client.send(data); // 向所有连接的客户端广播消息
                }
            });
        }
    });
    // ws.send(JSON.stringify({ message: 'something' }));
});

console.log('WebSocket 服务器已启动，监听端口 3300');

// 监听端口
app.listen(3000, () => {
    console.log("服务器启动成功,端口3000");
});
